<template>
  <div>
    <el-form :model="currentKnowledge">
      <el-row>
        <el-col :span="24">
          <el-form-item label="标题">
            <el-input v-model="currentKnowledge.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="标签">
            <div class="tags-container">
              <!-- 显示已选标签 -->
              <div class="selected-tags">
                <el-tag
                  v-for="(tagsItem, tagsItemindex) in currentKnowledge?.tags"
                  :key="tagsItemindex"
                  closable
                  @close="() => removetag(tagsItem, tagsItemindex)"
                  style="margin-right: 8px; margin-bottom: 8px;"
                >
                  {{ tagsItem?.name }}
                </el-tag>
              </div>
              
              <!-- 添加新标签 -->
              <el-input
                v-if="inputTagVisible"
                v-model="inputTagValue"
                ref="saveTagInput"
                size="small"
                style="width: 120px;"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
                placeholder="输入标签名"
              ></el-input>
              <el-button 
                v-else 
                class="button-new-tag" 
                size="small" 
                @click="showInput"
              >
                + 添加标签
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容">
            <ExcalidrawComponent
                ref="excalidrawComponent"
                :resourceJson="excalidrawData"
                :darkMode="true"
                :viewMode="false"
                :gridMode="true"
                :zenMode="false"
                height="600px"
                @change="_excalidrawData=>{
                  jsonData=_excalidrawData
                }"
            />
          </el-form-item>
        </el-col>

      </el-row>


    </el-form>


  </div>
</template>
<script>
import ExcalidrawComponent from "@/components/ExcalidrawComponent.vue";
import {deepClone} from "@/utils";
import * as knowledgeApi from '@/api/knowledge.api.js'
import {alertWithPaylod} from "@/utils/alertUtil";
import {nowWithFormat, safeParseJson} from '@/utils/index';

export default {
  data() {
    return {
      resourceJson: null,
      darkMode: true,
      viewMode: false,
      gridMode: true,
      zenMode: false,
      excalidrawLoaded: false,
      excalidrawData: null,
      jsonData: null,
      // 标签相关
      inputTagVisible: false,
      inputTagValue: '',
      tagsOptions: [],
      currentKnowledge: {
        name: '',
        content: '',
        tags: []
      },
    }
  },
  components: {
    ExcalidrawComponent
  },
  methods: {
    async initByDialog(_data) {
      this.id = _data?.id

      if (_data?.id) {
        this.currentKnowledge = await knowledgeApi?.getDetail(_data?.id)?.then(res => res?.data)
        console.log("=>(modify.vue:89) this.currentKnowledge", this.currentKnowledge);
        this.excalidrawData=this.currentKnowledge?.excalidraw
      }

      this.inittagsOptions()
    },
    /**
     * 显示标签输入框
     */
    showInput() {
      this.inputTagVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    /**
     * 确认添加标签
     */
    handleInputConfirm() {
      const inputValue = this.inputTagValue.trim();
      if (inputValue && !this.currentKnowledge.tags.some(tag => tag.name === inputValue)) {
        this.currentKnowledge.tags.push({ name: inputValue });
      }
      this.inputTagVisible = false;
      this.inputTagValue = '';
    },

    /**
     * 删除标签
     * @param {Object} tagsItem - 标签对象
     * @param {number} tagsItemindex - 标签在数组中的索引
     */
    async removetag(tagsItem, tagsItemindex) {
      // 检查标签是否有ID，如果没有ID说明是新添加的标签，直接从数组中移除
      if (!tagsItem?.id) {
        this.currentKnowledge?.tags.splice(tagsItemindex, 1)
        return
      }

      // 显示确认对话框
      try {
        await this.$confirm(`确定要删除标签 "${tagsItem.name}" 吗？`, '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 调用API删除标签
        const result = await knowledgeApi.deleteTag(tagsItem.id)
        
        if (result?.success) {
          // API调用成功，从本地数组中移除标签
          this.currentKnowledge?.tags.splice(tagsItemindex, 1)
          this.$message.success('标签删除成功')
        } else {
          // API调用失败，显示错误信息
          this.$message.error(result?.message || '删除标签失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          // 如果不是用户取消操作，则显示错误信息
          console.error('删除标签失败:', error)
          this.$message.error('删除标签失败，请重试')
        }
      }
    },
    inittagsOptions() {
    },

    async submitByDialog() {
      var params = deepClone(this.currentKnowledge)
      var excalidrawData = this.jsonData;
      params.excalidraw = excalidrawData;

      var func = params?.id ? knowledgeApi?.update : knowledgeApi?.add
      var resdult = await func(params)
      alertWithPaylod(resdult)

      return resdult;

    },

  }
}
</script>

<style scoped>
.tags-container {
  min-height: 32px;
}

.selected-tags {
  display: inline-block;
  margin-right: 8px;
}

.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
